import {Toast} from 'vant';

import createAxios from './js/axios.js';
// import translate from './translate/index.js';

export default () => {
    var util = new Object();

    util.browser = {
        language: (navigator.browserLanguage || navigator.language).toLowerCase(),
        runTime: () => {
            var u = navigator.userAgent;
            return {
                //移动终端浏览器版本信息
                trident: u.indexOf("Trident") > -1, //IE内核
                presto: u.indexOf("Presto") > -1, //opera内核
                webKit: u.indexOf("AppleWebKit") > -1, //苹果、谷歌内核
                gecko: u.indexOf("Gecko") > -1 && u.indexOf("KHTML") == -1, //火狐内核
                mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
                ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
                android: u.indexOf("Android") > -1 || u.indexOf("Linux") > -1, //android终端或uc浏览器
                iPhone: u.indexOf("iPhone") > -1, //是否为iPhone或者QQHD浏览器
                iPad: u.indexOf("iPad") > -1, //是否iPad
                webApp: u.indexOf("Safari") == -1, //是否web应该程序，没有头部与底部
                wechat: u.toLowerCase().match(/MicroMessenger/i) == "micromessenger"
            };
        },
        getUrlParam: (name) => {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]);
            return null;
        }
    };

    // 转入外部资源
    util.source = [];
    // params {mode, url, name, resolve, reject}
    // mode = script / link
    util.loadSourceUrl = (params) => {
        var loadSource = function (x) {
            if (util.source[x.name]) {
                x.resolve();
                return;
            }
            ;

            if (x.mode == "script") {
                var script = document.createElement("script");
                script.type = "text/javascript";
                script.src = x.url;
                script.onload = x.resolve;
                script.onerror = x.reject;
                script.setAttribute("remove", x.name);
                document.head.appendChild(script);
                util.source[x.name] = script;
            } else {
                var style = document.createElement("link");
                style.rel = "stylesheet";
                style.href = x.url;
                style.onload = x.resolve;
                style.onerror = x.reject;
                style.setAttribute("remove", x.name);
                document.head.appendChild(style);
                util.source[x.name] = style;
            }
        };

        if (typeof (params) == "array") {
            for (let x of params) {
                loadSource(x);
            }
        } else {
            loadSource(params);
        }
    };
    util.removeSourceOperate = (params) => {
        var removeSource = function (x) {
            var element = document.getElementsByTagName(x);
            for (let i = 0; i < element.length; i++) {
                if (element[i] && element[i].getAttribute("remove")) {
                    element[i].parentNode.removeChild(element[i]);
                }
            }
        };

        if (!params) {
            for (let x of ["script", "link"]) {
                removeSource(x);
            }
        }
    };

    // 请求数据集接口
    util.getRequestInterface = (path, params, callBack) => {
        var httpRequest = createAxios(),
            {url, requestSuccessOperate, requestFailOperate} = util.unifiedRequestOperate(path, callBack);

        httpRequest.get(url, {params}).then(requestSuccessOperate, requestFailOperate);
    };
    util.postRequestInterface = (path, params, callBack) => {
        var httpRequest = createAxios(),
            {url, requestSuccessOperate, requestFailOperate} = util.unifiedRequestOperate(path, callBack);
        //发送请求拿userInfo
        httpRequest.post(url, params).then(requestSuccessOperate, requestFailOperate);
    };
    util.postSystemGetlist = (path, params, callBack) => {
        var httpRequest = createAxios(),
            {url, requestSuccessOperate, requestFailOperate} = util.unifiedRequestOperate(path, callBack);

        httpRequest.post(url, params).then(requestSuccessOperate, requestFailOperate);
    };
    util.unifiedRequestOperate = (path, callBack) => {
        // var { url, beforeOperate } = util.requestBeforeDispose(path),
        var url = path, successCallBack = null, failCallBack = null, tipLoading = true;
        if (typeof (callBack) == 'function') {
            successCallBack = callBack;
            failCallBack = () => {
            };
        } else if (typeof (callBack) == 'object') {
            successCallBack = callBack.success;
            failCallBack = callBack.fail;
            tipLoading = (typeof (callBack.tip) == 'boolean') ? callBack.tip : true;
        }

        if (tipLoading) {
            Toast.loading({
                message: '加载中',
                duration: 0, forbidClick: true, loadingType: 'spinner'
            });
        }

        var requestSuccessOperate = (res) => {
            var code = Number(res.code);
            if (code == 200) {
                successCallBack(res);
                // callBack(beforeOperate(res));
                if (tipLoading) {
                    Toast.clear();
                }
            } else if (code == 400) {
                if (tipLoading) {
                    // Toast.success('暂无数据');
                    Toast.clear();
                    Toast.fail(res.msg);
                }
                failCallBack(res);
            } else {
                if (tipLoading) {
                    // Toast.fail('未知错误');
                    Toast.clear();
                    Toast.fail(res.msg);
                }
                failCallBack(res);
                util.defaultAbnormalSituation({
                    type: 'fail', event: 'console.print',
                    location: 'http.request.return.fail',
                    result: res
                });
            }
        };
        var requestFailOperate = (frs) => {
            if (tipLoading) {
                Toast.fail('请求失败');
                Toast.clear();
            }

            util.defaultAbnormalSituation(frs);
        };

        return {
            url, requestSuccessOperate, requestFailOperate
        };
    };
    // 前置处理
    util.requestBeforeDispose = (argue) => {
        var type = argue.substr(0, 1) == '/',
            beforeOperate = (data) => {
                return data
            };

        if (type) {
            return {
                url: argue, beforeOperate
            }
        } else {
            let np = argue.split('.'),
                obj = translate[np[0]][np[1]][np[2]];

            return {
                url: obj.interface,
                beforeOperate: (res) => {
                    return translate.buildMappingDataset(res, obj);
                }
            }
        }
    };

    // 默认的失败执行处理操作
    util.defaultAbnormalSituation = (response) => {
        var type = response.type || false,
            jsonStr = JSON.stringify(response);

        if (type) {
            let result = JSON.stringify(response.result);

            switch (response.event) {
                case 'alert':
                    alert(response.location + "\n" + result);
                    break;
                case 'console.print':
                    console.log(response.location + "：", result);
                    break;
            }
        } else {
            // Toast.fail()
            console.log(jsonStr);
        }
    };

    // 微信分享初始化操作
    util.requestLoadWeChatSDKOperate = (apiList) => {
        if (util.browser.runTime().wechat) {
            Toast.loading({
                message: '加载中',
                duration: 0, forbidClick: true, loadingType: 'spinner'
            });

            return new Promise((resolve, reject) => {
                util.loadSourceUrl({
                    mode: "script", name: "wx-js-sdk",
                    url: "http://res.wx.qq.com/open/js/jweixin-1.4.0.js",
                    resolve: () => {
                        resolve(apiList);
                    },
                    reject: reject
                });
            });
        } else {
            Toast.fail('此功能只可以在微信端使用');
            return Promise.reject();
        }
    };

    util.requestWeChatAuthorizeDataset = (apiList) => {
        return new Promise((resolve, reject) => {
            var url = "/api/wechat/jssdk",
                params = {
                    url: window.location.href.split("#")[0]
                };

            util.postRequestInterface(url, params, response => {
                // alert("Interface Result: " + JSON.stringify(response));
                let result = response.data,
                    // appId, timeStamp, noncestr, signature, apiList = []
                    config = {
                        debug: false,
                        appId: result.appId,
                        timestamp: result.timestamp,
                        nonceStr: result.noncestr,
                        signature: result.signature,
                        jsApiList: apiList || []
                    };
                // need edit
                // alert("WXSdk Config: " + JSON.stringify(config));
                // 成功
                wx.ready(res => {
                    // need edit
                    // alert("WXSdk Ready: " + JSON.stringify(res));
                    Toast.clear();
                    resolve();
                });
                // 失败
                wx.error(res => {
                    // need edit
                    alert("WXSdk Error: " + JSON.stringify(res));
                    reject(res);
                });
                // 初始化操作
                wx.config(config);
            });
        });
    };

    util.initializationWXScanQRCode = () => {
        return new Promise((resolve, reject) => {
            wx.scanQRCode({
                needResult: 1,
                scanType: ['qrCode', 'barCode'],
                success: function (res) {
                    resolve(res);
                },
                error: reject
            });
        });
    };

    util.initializationWXShare = (title, desc, image, url) => {
        wx.updateAppMessageShareData({
            title: title,
            desc: desc,
            link: url,
            imgUrl: image,
            success: resolve
        });
        wx.updateTimelineShareData({
            title: title,
            link: url,
            imgUrl: image,
            success: resolve
        });
    };

    return util;
};
